package com.zy.chat.aspect;

import com.zy.chat.dto.LoginFormDTO;
import com.zy.chat.entity.LoginLog;
import com.zy.chat.entity.UserLogin;
import com.zy.chat.mapper.LoginLogMapper;
import com.zy.chat.util.UserHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author zy
 * @date 2023/5/18 14:58
 */

@Aspect
@Component
public class LoginLogAspect {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private LoginLogMapper loginLogMapper;
    private Logger logger= LoggerFactory.getLogger(LoginLogAspect.class);

    @Around("@annotation(com.zy.chat.annotation.LoginLogging)")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Map<String, Object> loginResult = (Map<String, Object>) joinPoint.proceed();
        if (loginResult != null && !loginResult.isEmpty()) {
            String ip = request.getRemoteAddr();
            LocalDateTime loginTime = LocalDateTime.now();
            String methodName = joinPoint.getSignature().getName();
            UserLogin user =(UserLogin) loginResult.get("user");
            String username = user.getUsername();
            // 记录登录日志到数据库
            LoginLog loginLog = new LoginLog();
            loginLog.setUsername(username);
            loginLog.setLocalTime(loginTime);
            loginLog.setIpAddress(ip);
            System.out.println(loginLog);
            loginLogMapper.insert(loginLog);
            return joinPoint.proceed();
        } else {
            return null; // 或者抛出自定义异常
        }
    }
}
